package data.join.com.media;

import android.content.Context;
import android.text.TextUtils;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;

import data.join.com.carapi.ApiPref;
import data.join.com.database.bean.CommandBean;
import data.join.com.database.bean.CommandPref;
import data.join.com.database.bean.VideoBean;
import data.join.com.database.bean.VideoDBPref;
import data.join.com.media.VideoModule.VideoModule;
import data.join.com.network.RetrofitManager;
import data.join.com.network.gson.UpdateCommandRequest;
import data.join.com.service.MainService;
import data.join.com.utils.BaseThread;
import data.join.com.utils.FileUtils;
import data.join.com.utils.MyDate;
import data.join.com.utils.MyLog;
import data.join.com.utils.QiniuApi;
import data.join.com.utils.WakeLockUtils;
import retrofit2.Call;

/**
 * Created by Administrator on 2017/10/23.
 */

public class CommandHandleThread extends BaseThread{

    private static final String TAG = CommandHandleThread.class.getSimpleName();

    private static CommandHandleThread mInstance;

    private Context mContext;

    private CommandHandleThread(Context context){
        this.mContext = context;
    }

    public static CommandHandleThread getInstance(Context context){
        if(mInstance == null){
            mInstance = new CommandHandleThread(context);
        }
        return mInstance;
    }

    @Override
    public void run() {
        while (true){
            if(MainService.isNetWorkConnect(mContext,TAG)) {
                WakeLockUtils.getDefault(mContext).acquireWakeLock(TAG);
                handleCommand();
                WakeLockUtils.getDefault(mContext).releaseWakeLock(TAG);
            }
            await(TIME_WAIT);
        }
    }

    private void handleCommand(){
        while (true){
            CommandBean command = CommandPref.getInstance().getEarliestUnHandleCommand();

            if(command == null){
                MyLog.D(TAG, "command is NULL,no command need handle,break");
                break;
            }else {
                if(!handleCommand(command)){
                    break;
                }
            }
        }
    }

    private boolean handleCommand(CommandBean command){
        boolean ret;
        if (TextUtils.isEmpty(command.commandId)) {
            MyLog.E(TAG, "type.commandId is NULL");
            saveCommandState(command,CommandPref.HANDLE_STATE_ERROR);
            return true;
        }else{
            MyLog.D(TAG, "command id="+command.commandId+" is handing");
            if (TextUtils.isEmpty(command.cloudKey)) {
                String tempVideoPath = cutVideoByBean(command.getMediaId());

                if (TextUtils.isEmpty(tempVideoPath)) {
                    ret = handleCommandResult(command,"file not exist",CommandPref.HANDLE_STATE_ERROR);
                    return ret;
                } else {
                    QiniuApi.UploadResult uploadResult = QiniuApi.getDefault().startUploadAsync(tempVideoPath, QiniuApi.getQiniuToken(tempVideoPath,"video"));

                    if (uploadResult != null) {
                        command.cloudKey = uploadResult.cloudKey;
                        command.persistentId = uploadResult.persistentId;

                        try {
                            command.fSize = Long.toString(new File(tempVideoPath).length());
                        }catch (Exception e){
                            command.fSize = "0";
                        }

                        CommandPref.getInstance().updateCommandBean(command);
                    }
                    FileUtils.deleteFile(tempVideoPath);
                }
            }

            if (!TextUtils.isEmpty(command.cloudKey)) {
                ret = handleCommandResult(command,null,CommandPref.HANDLE_STATE_HANDLED);
            } else {
                ret = handleCommandResult(command,"文件上传七牛失败",CommandPref.HANDLE_STATE_ERROR);
            }
            return ret;
        }
    }

    private boolean handleCommandResult(CommandBean command,String error,int state){
        boolean ret;
        if (sendCommandResult(command, error)) {
            MyLog.D(TAG,"sendCommandResult success,error is "+error);
            saveCommandState(command,state);
            ret = true;
        } else {
            MyLog.E(TAG, "sendCommandResult fail,error is "+error);
            ret = false;
        }
        return ret;
    }

    private void saveCommandState(CommandBean command,int state){
        command.handleState = state;
        CommandPref.getInstance().updateCommandBean(command);
    }

    private boolean sendCommandResult(CommandBean commandBean, String error){
        boolean ret = false;

        UpdateCommandRequest commandRequest = new UpdateCommandRequest();
        HashMap<String,String> content = new HashMap<>();

        content.put("resource_id",commandBean.mediaId);
        content.put("key",commandBean.cloudKey);
        content.put("command_type",commandBean.type);
        content.put("persist_id",commandBean.persistentId);
        content.put("fsize",commandBean.fSize);

        commandRequest.content = content;
        commandRequest.error = error;

        Call<Object> objectCall = RetrofitManager.getApiService().updateCommand(commandBean.commandId,RetrofitManager.getBodyByJson(commandRequest));

        try {
            ret = objectCall.execute().isSuccessful();
        } catch (IOException e) {
            e.printStackTrace();
        }

        if(!ret){
            MyLog.E(TAG,"sendCommandResult first time fail,retry after 3 second!");
            await(3);
            objectCall = RetrofitManager.getApiService().updateCommand(commandBean.commandId,RetrofitManager.getBodyByJson(commandRequest));
            try {
                ret = objectCall.execute().isSuccessful();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return ret;
    }

    private String cutVideoByBean(String mediaId){
        String cutVideoPath = null;

        VideoBean videoBean = VideoDBPref.getInstance().getVideoByStringId(mediaId);

        if(videoBean != null && !TextUtils.isEmpty(videoBean.srcPath) && new File(videoBean.srcPath).exists()) {

            int cameraId = 0;
            if (videoBean.backOrFont == VideoModule.VIDEO_CAMERA_FRONT) {
                cameraId = 0;
            } else if (videoBean.backOrFont == VideoModule.VIDEO_CAMERA_BACK) {
                cameraId = 1;
            }

            int start = (int) (videoBean.startTime / 1000);
            int end = (int)(videoBean.endTime / 1000);
            MyLog.D(TAG,"videoBean.srcPath="+videoBean.srcPath);
            MyLog.D(TAG,"start="+ MyDate.getFormatTimeByLong(((long)start*1000))+",end="+MyDate.getFormatTimeByLong(((long)end*1000)));

            cutVideoPath = ApiPref.getInstance(mContext).takeVideo(cameraId, start,end);
        }
        return cutVideoPath;
    }

}
